<template>
  <div>
    <el-form label-width="120px">
      <el-form-item label="SPU名称">
        <el-input placeholder="请输入SPU名称" v-model="spuParams.spuName" />
      </el-form-item>
      <el-form-item label="SPU品牌">
        <el-select placeholder="请选择" v-model="spuParams.tmId">
          <el-option
            :label="trademark.tmName"
            :value="trademark.id"
            v-for="(trademark, index) in trademarkList"
            :key="trademark.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          placeholder="请输入SPU描述"
          v-model="spuParams.description"
        />
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          v-model:file-list="spuImageList"
          action="/api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img
            w-full
            :src="dialogImageUrl"
            style="width: 400px; height: 400px; margin: 0 auto; display: block"
          />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          :placeholder="
            unBaseSaleAttrList.length > 0
              ? `你还有${unBaseSaleAttrList.length}个未选择`
              : '没有可选的了'
          "
          v-model="unBaseSaleAttr"
        >
          <el-option
            :label="unBaseSaleAttr.name"
            :value="`${unBaseSaleAttr.id}:${unBaseSaleAttr.name}`"
            v-for="(unBaseSaleAttr, index) in unBaseSaleAttrList"
            :key="unBaseSaleAttr.id"
          />
        </el-select>
        <el-button
          :icon="Plus"
          type="primary"
          @click="addSaleAttr"
          :disabled="!unBaseSaleAttr"
          style="margin-left: 10px"
          >添加销售属性</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-table border :data="spuSaleAttrList">
          <el-table-column
            type="index"
            label="序号"
            width="80px"
            align="center"
          />
          <el-table-column prop="saleAttrName" label="属性值" width="160" />
          <el-table-column label="属性值名称列表">
            <template #="{ row, $index }">
              <el-tag
                v-for="(spuSaleAttrValue, index) in row.spuSaleAttrValueList"
                :key="spuSaleAttrValue.id"
                class="mx-1"
                closable
                :type="spuSaleAttrValue.id % 2 == 0 ? 'success' : ''"
                style="margin: 0 5px"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
              >
                {{ spuSaleAttrValue.saleAttrValueName }}
              </el-tag>
              <el-input
                v-if="row.flag"
                type="text"
                placeholder="请输入属性值"
                style="width: 100px"
                size="small"
                @blur="toLook(row)"
                v-model="row.inputValue"
                :ref="(el) => (inputAllRef[$index] = el)"
              ></el-input>
              <el-button
                v-else
                :icon="Plus"
                size="small"
                @click="toEdit(row, $index)"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160">
            <template #="{ row, $index }">
              <el-button
                type="danger"
                :icon="Delete"
                size="small"
                @click="spuSaleAttrList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveSpuHandler">保存</el-button>
        <el-button @click="cancelHandler">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, nextTick } from "vue";
import { Plus, Delete } from "@element-plus/icons-vue"; // 引入icon图标
import type { UploadProps, UploadUserFile } from "element-plus"; // 数据类型
import { ElMessage } from "element-plus";

import {
  reqBaseSaleAttrList,
  reqTrademarkList,
  reqSpuSaleAttrList,
  reqSpuImageList,
  reqAddOrUpdateSpu,
} from "@/api/product/spu"; // 请求函数
import type {
  IBaseSaleAttrList,
  ITrademarkList,
  ISpuSaleAttrList,
  ISpu,
  ISpuSaleAttr,
} from "@/api/product/spu/model"; // 数据类型

const emit = defineEmits(["changeScene"]);
const baseSaleAttrList = ref<IBaseSaleAttrList>([]); // 基础销售属性数据
const trademarkList = ref<ITrademarkList>([]); // 品牌数据
const spuSaleAttrList = ref<ISpuSaleAttrList>([]); // SPU销售属性数据
const spuImageList = ref<UploadUserFile[]>([]); // SPU图片列表数据
const unBaseSaleAttr = ref<string>(""); // 未选择的销售属性之一
const inputAllRef = ref<any>([]); // 添加属性值所有input框的实例
const spuParams = ref<ISpu>({
  category3Id: "",
  description: "",
  id: "",
  spuImageList: [],
  spuName: "",
  spuSaleAttrList: [],
  tmId: "",
}); // SPU添加或修改时的参数

// 计算SPU销售属性未选择的销售属性
const unBaseSaleAttrList = computed(() => {
  return baseSaleAttrList.value.filter((baseAttr) => {
    return spuSaleAttrList.value.every((spuAttr) => {
      return baseAttr.name !== spuAttr.saleAttrName;
    });
  });
});

/************ 照片墙相关的代码   ***************************/
const dialogImageUrl = ref(""); // 图片路劲
const dialogVisible = ref(false); // dialog对话框的状态

// 删除图片的回调
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  spuImageList.value = uploadFiles;
};

// 预览图片的回调
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
/********************************************************/

// 修改spu获取所需的数据
const updateSpuData = async (spu: ISpu) => {
  spuParams.value = spu;
  const BaseSaleAttrListData = reqBaseSaleAttrList();
  const TrademarkListData = reqTrademarkList();
  const SpuSaleAttrListData = reqSpuSaleAttrList(spu.id);
  const SpuImageListData = reqSpuImageList(spu.id);

  const result = await Promise.all([
    BaseSaleAttrListData,
    TrademarkListData,
    SpuSaleAttrListData,
    SpuImageListData,
  ]);

  baseSaleAttrList.value = result[0];
  trademarkList.value = result[1];
  spuSaleAttrList.value = result[2];
  spuImageList.value = result[3].map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    };
  });
};

// 添加销售属性按钮的回调
const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = unBaseSaleAttr.value.split(":");
  const newSaleAttr: ISpuSaleAttr = {
    baseSaleAttrId: Number(baseSaleAttrId),
    saleAttrName,
    spuSaleAttrValueList: [],
  };
  spuSaleAttrList.value.push(newSaleAttr);
  unBaseSaleAttr.value = "";
};

// input失焦切换查看模式
const toLook = (row: ISpuSaleAttr) => {
  if (!row.inputValue) {
    ElMessage({
      type: "error",
      message: "数据不能为空",
      showClose: true,
    });

    row.flag = false;
    return;
  }

  const result = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName == row.inputValue;
  });

  if (result) {
    ElMessage({
      type: "error",
      message: "数据已存在",
      showClose: true,
    });

    row.flag = false;
    return;
  }

  row.flag = false;

  const newSaleAttrValue = {
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrName: row.saleAttrName,
    saleAttrValueName: row.inputValue,
  };

  row.spuSaleAttrValueList.push(newSaleAttrValue);
};

// 点击添加属性值按钮切换编辑模式
const toEdit = (row: ISpuSaleAttr, index: number) => {
  row.flag = true;
  row.inputValue = "";
  nextTick(() => {
    inputAllRef.value[index].focus();
  });
};

// 保存新增或修改SPU按钮的回调
const saveSpuHandler = async () => {
  spuParams.value.spuImageList = spuImageList.value.map((item) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && (item.response as any).data) || item.url,
    };
  });

  spuSaleAttrList.value.forEach((item) => {
    if (item.flag) {
      delete item.flag;
    }
    if (item.inputValue) {
      delete item.inputValue;
    }
  });

  spuParams.value.spuSaleAttrList = spuSaleAttrList.value;

  try {
    await reqAddOrUpdateSpu(spuParams.value);

    ElMessage({
      type: "success",
      message: spuParams.value.id ? "修改成功" : "添加成功",
    });

    emit("changeScene", { cutScene: 0, flag: spuParams.value.id });
  } catch (error) {
    ElMessage({
      type: "error",
      message: spuParams.value.id ? "修改失败" : "添加失败",
    });
  }
};

// 添加spu获取所需数据
const addSpuData = async (category3Id: number | string) => {
  spuParams.value.category3Id = category3Id;
  const BaseSaleAttrListData = reqBaseSaleAttrList();
  const TrademarkListData = reqTrademarkList();
  const result = await Promise.all([BaseSaleAttrListData, TrademarkListData]);
  baseSaleAttrList.value = result[0];
  trademarkList.value = result[1];
};

// 清除修改或添加时所需的数据
const clearSpuData = () => {
  spuSaleAttrList.value = [];
  spuImageList.value = [];
  spuParams.value = {
    category3Id: "",
    description: "",
    id: "",
    spuImageList: [],
    spuName: "",
    spuSaleAttrList: [],
    tmId: "",
  };
};

// 取消按钮的回调
const cancelHandler = () => {
  emit("changeScene", { cutScene: 0, flag: spuParams.value.id });
  clearSpuData();
};

// 对外暴露方法
defineExpose({
  updateSpuData,
  addSpuData,
  clearSpuData
});
</script>
